package com.zxl.openapi.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zxl.openapi.constans.SystemParameter;
import com.zxl.openapi.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Map;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class CheckSignUsedFilter extends ZuulFilter {

    @Autowired
    private RedisService redisService;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 8;
    }

    @Override
    public boolean shouldFilter() {
        Map<String, Map<Object, Object>> allApiInfoMap = SystemParameter.allApiInfoMap;

        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        String method = request.getParameter("method");
        //获取当前接口的map
        Map<Object, Object> map = allApiInfoMap.get(SystemParameter.REDIS_APIPRE + method);
        //获取当前过滤器需要经过的filters
        String filters = (String) map.get("filters");

//        return false;
        return context.sendZuulResponse() && filters != null && filters.contains(getClass().getName());

        // return RequestContext.getCurrentContext().sendZuulResponse();

    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();

        String sign = request.getParameter("sign");

        String result = redisService.get(sign);

        if(result != null){

            currentContext.setSendZuulResponse(false);

            currentContext.setResponseBody("请不要重复请求");

            currentContext.getResponse().setContentType("text/html;charset=utf-8");

        }

        return null;

    }
}
